package com.efounder.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.core.xml.StubObject;
import com.efounder.chat.activity.SetWorkGroupActivity;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.SPUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.http.UniversalRequestManager;
import com.efounder.ospmobilelib.R;
import com.efounder.util.DialogUtil;
import com.efounder.util.HttpBase;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.RadarView;
import com.pansoft.resmanager.ResFileManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Hashtable;

/**
 * A simple {@link Fragment} subclass.
 */
public class BusinessAttendanceFragment extends BaseFragment implements AMapLocationListener {


    private LinearLayout ll_daka;
    private TextView tv_qiandao;
    private RelativeLayout rl_am;
    private RelativeLayout rl_amgone;
    private RelativeLayout rl_pm;
    private RelativeLayout rl_pmgone;
    private View view_top;
    private View view_bottom;
    private RadarView radarView;
    AMapLocationClient locationClient = null;
    private TextView amAddress;
    private TextView pmAddress;
    private TextView amTime;
    private TextView pmTime;

    private String userId;
    private String nickName;
    private String userName;
    private String passWord;
    private String mGroupId;
    private boolean isLoadData;//是否加载完数据了

//    标题栏
    private RelativeLayout rlTitle;
    private View viewLine;
    private ImageView ivTitleIcon;
    private TextView tvTitle;

    private StubObject mStubObject;
    private String mMenuIconStr;

    @SuppressLint("ValidFragment")
    public BusinessAttendanceFragment(StubObject object) {
        this.mStubObject = object;
    }

    public BusinessAttendanceFragment(){
        // Required empty public constructor

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation.getErrorCode() == AMapLocation.LOCATION_SUCCESS) {
//            System.out.println(("签到成功，签到经纬度：(" + aMapLocation.getLatitude() + "," + aMapLocation.getLongitude() + ")"));
            String province = aMapLocation.getProvince();
            String city = aMapLocation.getCity();
            String district = aMapLocation.getDistrict();
            String street = aMapLocation.getStreet();
            String streetNum = aMapLocation.getStreetNum();
            String addressString = city + district + street + streetNum;
            if (!tv_qiandao.getText().equals("签退")) {
                punchCardRequestServer(aMapLocation.getLongitude() + "", aMapLocation.getLatitude() + "", addressString, 0 + "");
                amSuccessView();
            } else {
                punchCardRequestServer(aMapLocation.getLongitude() + "", aMapLocation.getLatitude() + "", addressString, 1 + "");
                pmSuccessView();
            }
        } else {
            Toast.makeText(getActivity(), "签到失败，请重试...", Toast.LENGTH_SHORT).show();
            PunchCardFailedView();
            judgeState();
            //可以记录错误信息，或者根据错误错提示用户进行操作，Demo中只是打印日志
            Log.e("AMap", "签到定位失败，错误码：" + aMapLocation.getErrorCode() + ", " + aMapLocation.getLocationDetail());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_business_attendance, container, false);
        initView(view);
        initListener();
////        initLocationClient();
////        initUserInformation();
////        initTodayPunchCardData();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
//        initListener();

    }

    /**
     * 刷新界面
     */
    @Override
    public void onResume() {
        super.onResume();
//        initView();
        isLoadData = false;
        amPunchCardFailed();
        pmPunchCardFailed();
        initLocationClient();
        initUserInformation();
        initTodayPunchCardData();
    }

    /**
     * 初始化当天打卡数据
     */
    private void initTodayPunchCardData() {
        String time = getPunchCardInformation();

        String amTimeSP = (String) SPUtils.get(getContext(), "amTime"+mGroupId+"_"+userId, "");
        String pmTimeSP = (String) SPUtils.get(getContext(), "pmTime"+mGroupId+"_"+userId, "");

        if (!"".equals(amTimeSP)) {
            String[] split = amTimeSP.split("_");
            if (split.length == 3 && time.equals(split[0])) {
                String amSignTime = split[1];
                String amSignAddress = split[2];
                amPunchCardView();
                amSuccessView();
                amAddress.setText(amSignAddress);
                amTime.setText("签到时间 " + amSignTime);
            } else {
                requestOneDayPunchCardInformation(time);
            }
        } else {
            requestOneDayPunchCardInformation(time);
        }

        if (!"".equals(pmTimeSP)) {
            String[] split = pmTimeSP.split("_");
            if (split.length == 3 && time.equals(split[0])) {
                String pmSignTime = split[1];
                String pmSignAddress = split[2];
                pmPunchCardView();
                pmSuccessView();
                pmAddress.setText(pmSignAddress);
                pmTime.setText("签到时间 " + pmSignTime);
            } else {
                requestOneDayPunchCardInformation(time);
            }
        } else {
            requestOneDayPunchCardInformation(time);
        }
    }

    /**
     * 获取时间
     *
     * @return
     */
    private String getPunchCardInformation() {
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;
        int day = now.get(Calendar.DAY_OF_MONTH);
        String time = "" + year;
        if (month <= 9) {
            time = time + "0" + month;
        } else {
            time = time + month;
        }
        if (day <= 9) {
            time = time + "0" + day;
        } else {
            time = time + day;
        }

        return time;
    }

    /**
     * 初始化用户信息
     */
    private void initUserInformation() {
        userId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        mGroupId = EnvironmentVariable.getProperty(userId + "workgroup");
        nickName = EnvironmentVariable.getProperty(Constants.KEY_NICK_NAME);
        userName = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        passWord = EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD);
    }

    /**
     * 初始化LocationClient
     */
    private void initLocationClient() {
        locationClient = new AMapLocationClient(getActivity().getApplicationContext());
        AMapLocationClientOption option = new AMapLocationClientOption();
        /**
         * 设置签到场景，相当于设置为：
         * option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
         * option.setOnceLocation(true);
         * option.setOnceLocationLatest(true);
         * option.setMockEnable(false);
         * option.setWifiScan(true);
         * option.setGpsFirst(false);
         * 其他属性均为模式属性。
         * 如果要改变其中的属性，请在在设置定位场景之后进行
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        locationClient.setLocationOption(option);
        //设置定位监听
        locationClient.setLocationListener(this);
    }

    private void initView(View view) {
        ll_daka = (LinearLayout) view.findViewById(R.id.daka);
        tv_qiandao = (TextView) view.findViewById(R.id.qiandao);
        rl_am = (RelativeLayout) view.findViewById(R.id.amcontent);
        rl_amgone = (RelativeLayout) view.findViewById(R.id.amcontent_gone);
        rl_pm = (RelativeLayout) view.findViewById(R.id.pmcontent);
        rl_pmgone = (RelativeLayout) view.findViewById(R.id.pmcontent_gone);
        view_top = view.findViewById(R.id.lefttop);
        view_bottom = view.findViewById(R.id.leftbottom);
        radarView = (RadarView) view.findViewById(R.id.radarView);
        amTime = (TextView) view.findViewById(R.id.tv_amtime);
        pmTime = (TextView) view.findViewById(R.id.tv_pmtime);
        amAddress = (TextView) view.findViewById(R.id.am_address);
        pmAddress = (TextView) view.findViewById(R.id.pm_address);

        rlTitle = (RelativeLayout) view.findViewById(R.id.title);
        ivTitleIcon = (ImageView) view.findViewById(R.id.card);
        tvTitle = (TextView) view.findViewById(R.id.tv_frag_title);
        viewLine = view.findViewById(R.id.line);


        if (mStubObject != null) {
            Hashtable stubTable = mStubObject.getStubTable();
//            mGroupId = Integer.valueOf((String) stubTable.get("groupId"));
            if (stubTable.containsKey("caption")) {
                tvTitle.setText((String) stubTable.get("caption"));
            } else {
                rlTitle.setVisibility(View.GONE);
                viewLine.setVisibility(View.GONE);
            }
            if (stubTable.containsKey("menuIcon")) {
                mMenuIconStr = "file://" + ResFileManager.IMAGE_DIR + "/" + (String) stubTable.get("menuIcon");
                LXGlideImageLoader.getInstance().displayImage(getContext(), ivTitleIcon, mMenuIconStr, R.drawable.iframe_icon_refresh, R.drawable.iframe_icon_refresh);
            } else {
                rlTitle.setVisibility(View.GONE);
                viewLine.setVisibility(View.GONE);
            }
        }
    }

    private void initListener() {
        ll_daka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isLoadData){
                    return;
                }
                if (EnvironmentVariable.getProperty(userId + "workgroup") == null
                        || "".equals(EnvironmentVariable.getProperty(userId + "workgroup"))) {
                    new android.app.AlertDialog.Builder(getActivity())
                            .setMessage("您还未设置工作群,请前往设置")
                            .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    getActivity().startActivity(new Intent(getActivity(), SetWorkGroupActivity.class));
                                }
                            }).show();
                }else {
//                    mGroupId = EnvironmentVariable.getProperty(userId + "workgroup");
                    if (tv_qiandao.getText().equals("签到")) {
                        amPunchCardView();
                        //签到只需调用startLocation即可
                        locationClient.startLocation();
                    } else if (tv_qiandao.getText().equals("签退")) {
                        pmPunchCardView();
                        locationClient.startLocation();
                    }
                }


            }
        });
    }

    /**
     * 打卡请求
     *
     * @param longgitude
     * @param latitude
     * @param positionName
     * @param operLabel
     */
    private void punchCardRequestServer(String longgitude, String latitude, final String positionName, final String operLabel) {
//        mGroupId = EnvironmentVariable.getProperty(userId + "workgroup");

        if (EnvironmentVariable.getProperty(userId + "workgroup") == null
                || "".equals(EnvironmentVariable.getProperty(userId + "workgroup"))) {
            return;
        }

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("userid", userId);
        paramsMap.put("groupid", mGroupId);
        paramsMap.put("longgitude", longgitude);
        paramsMap.put("latitude", latitude);
        paramsMap.put("positionname", positionName);
        paramsMap.put("operlabel", operLabel);
        UniversalRequestManager.getInstance(getActivity()).requestAsyn(HttpBase.GROUP_WORK_CARD_BASEURL + HttpBase.CLOCKIN, 1, paramsMap, new UniversalRequestManager.ReqCallBack<Object>() {

            @Override
            public void onReqSuccess(Object result) {
                String s = result.toString();

                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String requestResult = jsonObject.getString("result");
                    if ("success".equals(requestResult)) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        String operTime = data.getString("operTime");
                        String time = switchTime(operTime);
                        if ("0".equals(operLabel)) {
                            amAddress.setText(positionName);
                            amTime.setText("签到时间 " + time);
                            amTime.setVisibility(View.VISIBLE);
                            SPUtils.put(getContext(), "amTime"+mGroupId+"_"+userId, getPunchCardInformation() + "_" + time + "_" + positionName);
                        } else {
                            pmAddress.setText(positionName);
                            pmTime.setText("签退时间 " + time);
                            amTime.setVisibility(View.VISIBLE);
                            SPUtils.put(getContext(), "pmTime"+mGroupId+"_"+userId, getPunchCardInformation() + "_" + time + "_" + positionName);

                        }
                    } else {
                        Toast.makeText(getContext(), "签到失败，请重试...", Toast.LENGTH_SHORT).show();
                        PunchCardFailedView();
                    }
                } catch (JSONException e) {
                    Toast.makeText(getContext(), "数据解析失败，请重试...", Toast.LENGTH_SHORT).show();
                    PunchCardFailedView();
                    e.printStackTrace();
                }
                System.out.println("结果==>" + s);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Toast.makeText(getContext(), "请求服务器失败，请重试...", Toast.LENGTH_SHORT).show();
                PunchCardFailedView();
            }
        });
    }

    /**
     * 获取某天打卡信息
     *
     * @param operdate
     */
    public void requestOneDayPunchCardInformation(String operdate) {
        if (EnvironmentVariable.getProperty(userId + "workgroup") == null
                || "".equals(EnvironmentVariable.getProperty(userId + "workgroup"))) {
            return;
        }
//        mGroupId = EnvironmentVariable.getProperty(userId + "workgroup");

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("userid", userId);
        paramsMap.put("groupid", mGroupId);
        paramsMap.put("operdate", operdate);
        UniversalRequestManager.getInstance(getActivity()).requestAsyn(HttpBase.GROUP_WORK_CARD_BASEURL + HttpBase.ONEDAY, 0, paramsMap, new UniversalRequestManager.ReqCallBack<Object>() {

            @Override
            public void onReqSuccess(Object result) {
                String s = result.toString();
                isLoadData = true;
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String requestResult = jsonObject.getString("result");
                    if ("success".equals(requestResult)) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        int length = data.length();
                        if (length == 0) {
                            //此日期未打卡

                        } else if (length == 1) {
                            //此日期上午打过卡了
                            JSONObject jsonObject1 = data.getJSONObject(0);
                            String positionName = jsonObject1.getString("positionName");
                            String operTime = jsonObject1.getString("operTime");
                            String time = switchTime(operTime);

                            amPunchCardView();
                            amSuccessView();
                            amAddress.setText(positionName);
                            amTime.setText("签到时间 " + time);
                        } else {
                            //此日期全天打过卡了
                            JSONObject jsonObject1 = data.getJSONObject(0);
                            String positionName = jsonObject1.getString("positionName");
                            String operTime = jsonObject1.getString("operTime");
                            String time = switchTime(operTime);

                            amPunchCardView();
                            amSuccessView();
                            amAddress.setText(positionName);
                            amTime.setText("签到时间 " + time);

                            JSONObject jsonObject2 = data.getJSONObject(1);
                            String positionName2 = jsonObject2.getString("positionName");
                            String operTime2 = jsonObject2.getString("operTime");
                            String time2 = switchTime(operTime2);

                            pmPunchCardView();
                            pmSuccessView();
                            pmAddress.setText(positionName2);
                            pmTime.setText("签到时间 " + time2);

                        }

                    } else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                System.out.println("结果==>" + s);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                isLoadData = true;
            }
        });
    }

    /**
     * 时间转换
     *
     * @param operTime
     * @return
     */
    private String switchTime(String operTime) {
        int length = operTime.length();
        String h = "00";
        String m = "00";
        if (length == 0 || length == 1 || length == 2) {
            h = "00";
            m = "00";
        } else if (length == 3) {
            h = "00";
            m = "0" + operTime.charAt(0);
        } else if (length == 4) {
            h = "00";
            m = operTime.charAt(0) + "" + operTime.charAt(1);
        } else if (length == 5) {
            h = "0" + operTime.charAt(0);
            m = operTime.charAt(1) + "" + operTime.charAt(2);
        } else if (length == 6) {
            h = operTime.charAt(0) + "" + operTime.charAt(1);
            m = operTime.charAt(2) + "" + operTime.charAt(3);
        }
        return h + ":" + m;
    }

    /**
     * 签退view
     */
    private void pmPunchCardView() {
        pmTime.setText("正在定位...");
        rl_pmgone.setVisibility(View.VISIBLE);
        rl_pm.setVisibility(View.GONE);
        tv_qiandao.setVisibility(View.GONE);
        radarView.setVisibility(View.VISIBLE);
        radarView.setSearching(true);
    }

    /**
     * 签退成功view
     */
    private void pmSuccessView() {
        tv_qiandao.setText("完成");
        tv_qiandao.setVisibility(View.VISIBLE);
        view_bottom.setBackgroundResource(R.drawable.background_round);
        radarView.setVisibility(View.GONE);
        radarView.setSearching(false);
    }

    /**
     * 点击签到
     */
    private void amPunchCardView() {
        amTime.setText("正在定位...");
        rl_amgone.setVisibility(View.VISIBLE);
        rl_am.setVisibility(View.GONE);
        tv_qiandao.setVisibility(View.GONE);
        radarView.setVisibility(View.VISIBLE);
        radarView.setSearching(true);
    }

    /**
     * 签到成功view
     */
    private void amSuccessView() {
        tv_qiandao.setText("签退");
        tv_qiandao.setVisibility(View.VISIBLE);
        view_top.setBackgroundResource(R.drawable.background_round);
        radarView.setVisibility(View.GONE);
        radarView.setSearching(false);
    }

    /**
     * 签到失败view
     */
    private void amPunchCardFailed() {
        amTime.setText("新的一天，从良好的工作习惯开始");
        rl_amgone.setVisibility(View.GONE);
        rl_am.setVisibility(View.VISIBLE);
        tv_qiandao.setVisibility(View.VISIBLE);
        radarView.setVisibility(View.GONE);
        radarView.setSearching(false);
        tv_qiandao.setText("签到");
    }

    /**
     * 签退失败view
     */
    private void pmPunchCardFailed() {
        pmTime.setText("下班打卡");
        rl_pmgone.setVisibility(View.GONE);
        rl_pm.setVisibility(View.VISIBLE);
        tv_qiandao.setVisibility(View.VISIBLE);
        radarView.setVisibility(View.GONE);
        radarView.setSearching(false);
        tv_qiandao.setText("签到");
    }

    /**
     * 打卡失败
     */
    private void PunchCardFailedView() {
        if (tv_qiandao.getText().equals("签退")) {
            pmPunchCardFailed();
        } else {
            amPunchCardFailed();
        }
    }

    /**
     * 判断gps开关
     */
    private void judgeState() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        boolean isopenGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean netWork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!isopenGPS && wifiManager.isWifiEnabled()) {
            DialogUtil.showDialog(getActivity(), "请打开GPS开关", "打开GPS开关，即可获得精确定位", ResStringUtil.getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 2920);
                }
            }, ResStringUtil.getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //销毁时，需要销毁定位client
        if (null != locationClient) {
            locationClient.onDestroy();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 2920) {
//            intent = new Intent(this,ZYWorkCardActivity.class);
//            finish();
//            startActivity(intent);
//            this.overridePendingTransition(0, 0);
//        }
    }
}
